package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.pojo.PurchaseSupplier;
import com.intelligent.pojo.TUser;
import com.intelligent.service.PurchaseSupplierService;
import com.intelligent.service.TUserService;
import com.intelligent.dto.PurchaseSupplierQueryDTO;
import com.intelligent.dto.PurchaseSupplierAddDTO;
import com.intelligent.vo.PurchaseSupplierVO;
import com.intelligent.mapper.PurchaseSupplierMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Service
public class PurchaseSupplierServiceImpl extends ServiceImpl<PurchaseSupplierMapper, PurchaseSupplier>
    implements PurchaseSupplierService{

    @Autowired
    private TUserService userService;

    @Override
    public IPage<PurchaseSupplierVO> pageList(PurchaseSupplierQueryDTO query) {
        Page<PurchaseSupplier> page = new Page<>(
            query.getPageNum() != null ? query.getPageNum() : 1,
            query.getPageSize() != null ? query.getPageSize() : 10
        );

        LambdaQueryWrapper<PurchaseSupplier> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(query.getKeyword())) {
            wrapper.and(w -> w
                .like(PurchaseSupplier::getSupplierCode, query.getKeyword())
                .or()
                .like(PurchaseSupplier::getSupplierName, query.getKeyword())
            );
        }

        if (StringUtils.isNotBlank(query.getSupplierCode())) {
            wrapper.like(PurchaseSupplier::getSupplierCode, query.getSupplierCode());
        }

        if (StringUtils.isNotBlank(query.getSupplierName())) {
            wrapper.like(PurchaseSupplier::getSupplierName, query.getSupplierName());
        }

        if (query.getStatus() != null) {
            wrapper.eq(PurchaseSupplier::getStatus, query.getStatus());
        }


        IPage<PurchaseSupplier> supplierPage = this.page(page, wrapper);

        return supplierPage.convert(supplier -> {
            PurchaseSupplierVO vo = new PurchaseSupplierVO();
            BeanUtils.copyProperties(supplier, vo);

            if (supplier.getUId() != null) {
                TUser user = userService.getById(supplier.getUId());
                if (user != null) {
                    vo.setContactName(user.getUsername());
                }
            }

            vo.setStatusText(getStatusText(supplier.getStatus()));

            return vo;
        });
    }

    @Override
    public boolean addSupplier(PurchaseSupplierAddDTO addDTO) {
        if (addDTO == null) {
            throw new IllegalArgumentException("新增数据不能为空");
        }

        if (StringUtils.isBlank(addDTO.getSupplierName())) {
            throw new IllegalArgumentException("供应商名称不能为空");
        }

        // 检查供应商名称是否已存在
        LambdaQueryWrapper<PurchaseSupplier> nameWrapper = new LambdaQueryWrapper<>();
        nameWrapper.eq(PurchaseSupplier::getSupplierName, addDTO.getSupplierName());
        if (this.count(nameWrapper) > 0) {
            throw new IllegalArgumentException("供应商名称已存在");
        }

        // 检查联系人是否存在
        if (addDTO.getUId() != null) {
            TUser user = userService.getById(addDTO.getUId());
            if (user == null) {
                throw new IllegalArgumentException("联系人不存在");
            }
        }

        // 自动生成供应商编号
        String supplierCode = generateSupplierCode();

        // 创建供应商实体
        PurchaseSupplier supplier = new PurchaseSupplier();
        BeanUtils.copyProperties(addDTO, supplier);
        supplier.setSupplierCode(supplierCode);

        // 设置默认状态（如果未设置）
        if (supplier.getStatus() == null) {
            supplier.setStatus(0);
        }

        return this.save(supplier);
    }

    private String generateSupplierCode() {
        LocalDate today = LocalDate.now();
        String dateStr = today.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        LambdaQueryWrapper<PurchaseSupplier> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(PurchaseSupplier::getSupplierCode, "GY" + dateStr);
        long count = this.count(wrapper);

        return "GY" + dateStr ;
    }

    private String getStatusText(Integer status) {
        if (status == null) {
            return "未知";
        }
        switch (status) {
            case 0:
                return "启用";
            case 1:
                return "停用";
            default:
                return "未知";
        }
    }
}
